package com.lucy.nepu.module.htopic.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.Validator;
import com.lucy.common.constant.HttpStatus;
import com.lucy.common.domain.ResponseDTO;
import com.lucy.nepu.loader.PeriodLoader;
import com.lucy.nepu.module.htopic.constant.HorTopicTypeConst;
import com.lucy.nepu.module.htopic.entity.HorTopic;
import com.lucy.nepu.module.htopic.lib.HorTopicDict;
import com.lucy.nepu.module.htopic.lib.HorTopicDictService;
import com.lucy.nepu.module.htopic.params.HorTopicCreateParams;
import com.lucy.nepu.module.htopic.params.HorTopicQueryParams;
import com.lucy.nepu.module.htopic.service.HorTopicService;
import com.lucy.nepu.utils.ValidUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author kindear
 * 横向课题API
 */
@RestController
@RequestMapping("nepu")
@Api(tags = "横向课题")
public class HorTopicController {

    @Autowired
    HorTopicService service;

    @Autowired
    HorTopicDictService dictService;

    @Autowired(required = false)
    PeriodLoader periodLoader;

    @PostMapping("htopics")
    @ApiOperation(value = "横向课题新建",notes = "")
    public ResponseDTO<Object> horTopicCreate(@RequestBody @Validated HorTopicCreateParams params){
        // 1. 表单校验
        String errMsg = ValidUtil.formValid(params);
        if (!Validator.isEmpty(errMsg)){
            return ResponseDTO.wrap(HttpStatus.BAD_REQUEST,errMsg);
        }
        // 2. 获取当前时间所在周期ID -- 自动拦截不在时间段内的提交
        String periodId = periodLoader.getPeriodId();
        // 3. 获取词典信息 -- 修改为计算形式
        String horTopicType = params.getHorTopicType();
        HorTopicDict dict = new HorTopicDict();
        dict.setHorTopicType(horTopicType);
        Example<HorTopicDict> example = Example.of(dict);
        List<HorTopicDict> dicts = dictService.getExample(example);
        // 过滤
        Double funds = params.getFunds();
        dicts = dicts.stream().filter(ele-> ele.getFundsFloor() <= funds && ele.getFundsCeiling() >= funds).collect(Collectors.toList());
        if (dicts.size() == 0){
            return ResponseDTO.wrap(HttpStatus.NOT_FOUND,"没有满足条件的词典信息");
        }
        dict = dicts.get(0);
        // 4. 写入记录 并赋值最大工作量
        HorTopic topic = new HorTopic();
        topic.setPeriodId(periodId);
        topic.setHorTopicDictId(dict.getId());
        BeanUtil.copyProperties(params,topic, CopyOptions.create().setIgnoreError(true).setIgnoreNullValue(true));
        // 自然科学 -- 和经费正相关
        Double workload = 0.0;

        if (topic.getHorTopicType().equals(HorTopicTypeConst.NATURAL)){
            workload = topic.getFunds();
        }
        else if (topic.getHorTopicType().equals(HorTopicTypeConst.SOCIAL)){
            workload = dict.getWorkloadMax();
        }
        topic.setWorkload(workload);

        HorTopic saveRes = service.saveOne(topic);

        return ResponseDTO.succData(saveRes);
    }

    @DeleteMapping("htopics/{id}")
    @ApiOperation(value = "横向课题删除",notes = "")
    public ResponseDTO<Object> horTopicDelete(@PathVariable("id") String id){
        HorTopic topic = service.getOneUnwrap(id);
        if (topic.getStatus().equals(2)){
            return ResponseDTO.wrap(HttpStatus.FORBIDDEN,"锁定记录，无法操作");
        }
        service.deleteOne(id);
        return ResponseDTO.succMsg("删除成功");
    }

    @GetMapping("htopics")
    @ApiOperation(value = "横向课题列表")
    public ResponseDTO<Object> horTopicListQuery(HorTopicQueryParams params){
        Sort sort;
        if("DESC".equalsIgnoreCase(params.getOrder())){
            sort = Sort.by(Sort.Direction.DESC, params.getSortBy());
        }else {
            sort = Sort.by(Sort.Direction.ASC, params.getSortBy());
        }

        // tips : 页码对应 - 1
        Pageable pageable = PageRequest.of(params.getPageNum() - 1 , params.getPageSize(), sort);
        /*
        构建 Example
         */
        HorTopic o = new HorTopic();
        BeanUtil.copyProperties(params,o,CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        Example<HorTopic> example = Example.of(o);
        return ResponseDTO.succData(service.getAll(pageable,example));
    }


}
